<?php
declare(strict_types=1);

namespace App\AdminApi\Api;

use App\AdminApi\AdminApiBasicsController;
use App\AdminApi\Module\Admin\Service\UserService;
use App\Common\Guard\AdminGuard;
use App\Sys;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;
use Zms\AdminElementPlus\FormCreate\Form;
use Zms\AdminElementPlus\FormCreate\FormItem;
use Zms\Guard\Auth;
use zms\HyperfResponse\Response;
use Zms\Validate\Validate;
use function Hyperf\Support\make;

#[
    Controller(prefix: '/admin-api/person', server: self::SERVER),
    Auth(guard: self::GUARD, sign: "skip", app: self::APP)
]
class PersonController extends AdminApiBasicsController
{
    #[
        PostMapping('edit-data'),
        Auth(label: ['修改账号资料'], logger: 'POST', record: ['account'])
    ]
    public function EditData(): ResponseInterface
    {
        $user = $this->user();
        if ($this->request->isMethod('GET')) {
            $rule[] = FormItem::Input('nickname', '管理员昵称', $user->nickname)->clearable(true)->maxlength(20)->required('请输入管理员昵称');
            $rule[] = FormItem::Input('account', '登录账号', $user->account)->placeholder('后台登录账号')->clearable(true)->required('请输入后台登录账号')->maxlength(30);
            $rule[] = FormItem::ImageInput('avatar', '账号头像', $user->avatar)->required('请设置账号头像')->clearable(true);
            $form = Form::create('修改账号资料')->setRules($rule)->setOptionFormInline(true);
            return Response::Api()->success(data: $form->toArray());
        }
        $validate = make(Validate::class)
            ->setLabels(['nickname' => '管理员昵称', 'account' => '登录账号', 'avatar' => '账号头像'])
            ->setRules([
                ['nickname', 'required', 'on' => ['created', 'updated']],
                ['nickname', 'string', 'max' => 20, 'on' => ['created', 'updated']],

                ['account', 'required', 'error' => '{label}不能为空', 'on' => ['created']],
                ['account', 'string', 'min' => 5, 'max' => 30, 'on' => ['created', 'updated']],

                ['avatar', 'required', 'on' => ['created', 'updated']],
                ['avatar', 'string', 'on' => ['created', 'updated']],
            ])
            ->setData($this->request->inputs(['nickname', 'account', 'avatar']))->validate();
        if ($validate->isFail()) {
            return Response::Api()->fail($validate->firstError());
        }
        $data = $validate->getSafeData();
        $data['id'] = $user->getId();
        if (Sys::container(UserService::class)->updated($data)) {
            return Response::Api()->success('资料修改成功', $data);
        }
        return Response::Api()->fail('资料资料失败');
    }


    #[
        PostMapping('edit-passwd'),
        Auth(label: ['修改登录密码'], logger: 'POST', record: ['account']),
        \Zms\HyperfValidateAnnotations\Validate(
            rules: [
                [['old_password', 'password', 'password2'], 'required'],
                ['password', 'compare', 'find' => 'password2']
            ],
            labels: [
                'old_password' => '旧密码',
                'password' => '新密码',
                'password2' => '确认密码'
            ]
        )
    ]
    public function EditPasswd(): ResponseInterface
    {
        $old_password = $this->request->input('old_password');
        $password = $this->request->input('password');

        /**
         * 验证密码安全性
         */
        $error = Sys::container(UserService::class)->checkPassword($password);
        if ($error !== true) {
            return Response::Api()->fail($error);
        }

        /**
         * @var AdminGuard $admin
         */
        $admin = AdminGuard::where(['id' => $this->user()->getId()])->first();
        if ($admin->verifyPassword($old_password, $admin->password, $admin->secret_key) === false) {
            return Response::Api()->fail('旧密码错误');
        }
        $admin->secret_key = $admin->generateSecretKey();
        $admin->password = $admin->generatePassword($password, $admin->secret_key);
        if ($admin->save()) {
            return Response::Api()->success('密码修改成功,请重新登录');
        }
        return Response::Api()->fail('密码修改失败');
    }
}